<template>
    <div class="page-container" v-loading="loading.dataStatus" element-loading-text="正在加载...">
        <el-row>
            <el-col :span="14">
                <el-button type="primary"  @click="showAddDialog = true"><i class="fa fa-plus"></i> 添加管理员</el-button>
                <el-button type="warning"   @click="removeSelection"><i class="fa fa-remove"></i> 删除选中</el-button>
            </el-col>
            
                <div class="right-search-box">
                    <el-input placeholder="请输入条件"  v-model="keyword"  @keyup.enter.native="findAdmin">
                        <el-select v-model="select" slot="prepend" placeholder="请选择">
                            <el-option label="用户名" value="1" ></el-option>
                        </el-select>
                        <el-button slot="append" icon="search" @click="findAdmin"></el-button>
                    </el-input>
                </div>
            
        </el-row>
        <el-row>
            <el-table :data="tableData" style="width: 100%"  @selection-change='handleSelectionChange' :border="true">
                <el-table-column
                    type="selection"
                    width="40">
                </el-table-column>
                <el-table-column
                    prop="UserName"
                    label="用户名"
                    width="180">
                </el-table-column>
                <el-table-column
                    prop="Status"
                    label="状态"
                    width="80">
                     <template scope="scope">
                        <el-tag :type="scope.row.Status === 1 ? 'success' : 'warning'"
                        close-transition>{{scope.row.Status == 1?"正常":"禁用"}}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="CreatedOn"
                    label="添加时间">
                </el-table-column>
                <el-table-column label="操作" width="180">
                    <template scope="scope">
                        <el-button size="mini" type="danger" @click="removeAdmin(scope.$index,scope.row)"><i class="fa fa-remove"></i> 删除 </el-button>
                        <el-button size="mini" type="danger" @click="disableAdmin(scope.$index,scope.row)" v-if="scope.row.Status === 1"><i class="fa fa-hand-stop-o"></i> 禁用 </el-button>
                        <el-button size="mini" type="warning" @click="enableAdmin(scope.$index,scope.row)" v-if="scope.row.Status !== 1"><i class="fa fa-thumbs-up"></i> 启用 </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-row>
        <el-row style="text-align:center">
            <el-pagination v-if="totalPage > 1"
                @current-change="handleCurrentChange"
                :current-page.sync="currentPage"
                :page-size="pageSize"
                layout="total, prev, pager, next"
                :total="totalCount">
            </el-pagination>
        </el-row>
        
        <el-dialog title="添加管理员" custom-class="addDialog" :visible.sync="showAddDialog" :close-on-click-modal="false" :show-close="false" @close="dialogClose" v-loading="loading.formStatus" element-loading-text="正在提交...">
            <el-form :model="adminForm" :rules="formRules" ref="adminForm" :label-width="formLabelWidth" >
                <el-form-item label="登录名" prop="userName" >
                    <el-input type="text" v-model="adminForm.userName" autofocus="true"  auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input type="password" v-model="adminForm.password" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                    <el-input type="password" v-model="adminForm.confirmPassword" auto-complete="off" @keyup.enter.native="submitAddAdmin('adminForm')"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="showAddDialog = false"><i class="fa fa-power-off"></i> 取 消</el-button>
                <el-button type="primary" @click="submitAddAdmin('adminForm')"><i class="fa fa-save "></i> 确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

 <script>
    export default {
        data() {
            var validateUserName = (rule,value,callback)=>{
                if (value === '') {
                    callback(new Error('请输入登录名'));
                } else {
                    var regx = /^[a-z|A-Z|0-9]{4,20}$/;
                    if(!regx.test(value)){
                        callback(new Error('登录名必须是4-20个英文、数字字符的组合'));
                    }
                    callback();
                }
            };
            var validatePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入密码'));
                } else {
                    callback();
                }
            }
            var validatePassConfirm = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入密码'));
                } else if (value !== this.adminForm.password) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            }
            return {
                tableData: [],//表格数据
                selectionData : [],//被选择的数据
                adminForm:{
                    userName:'',
                    password:'',
                    confirmPassword:''
                },
                formRules: {
                    userName: [
                        { required:true,validator:validateUserName, trigger: 'blur' }
                    ],
                    password: [
                        { required:true,validator:validatePass, trigger: 'blur' }
                    ],
                    confirmPassword: [
                        { required:true,validator:validatePassConfirm, trigger: 'blur' }
                    ]
                },
                loading:{
                    formStatus : false,//表单loading
                    dataStatus : false //列表loading
                },
                formLabelWidth: '90px',
                currentPage: 1,
                pageSize:15,
                totalCount:0,
                totalPage:0,
                showAddDialog:false,
                select:'1',
                keyword:''
            }
        },
        methods: {
                getData(){
                    this.loading.dataStatus = true
                    this.$$api_permission_GetAdminList(
                        {pageIndex:this.currentPage,pageSize:this.pageSize},
                        data=>{
                                this.loading.dataStatus = false
                                this.currentPage = data.PageIndex
                                this.totalPage = data.TotalPage
                                this.totalCount = data.TotalCount
                                this.tableData= data.DataList
                              },
                              {
                                errFn:()=>{
                                     this.loading.dataStatus = false
                                }
                              }
                    )
                },
                submitAddAdmin(formName){
                     this.$refs[formName].validate((valid) => {
                            if (valid) {
                                this.loading.formStatus = true;
                                this.$$api_permission_CreateAdmin(this.adminForm,data=>{
                                    this.showAddDialog = false
                                    this.loading.formStatus = false
                                    this.$message({
                                            type: 'success',
                                            message: '添加成功!'
                                    });
                                    this.getData();
                                },
                                {
                                    errFn:()=>{
                                        this.loading.formStatus = false
                                    }
                                })
                            } 
                    })
                },
                findAdmin(){
                    if(this.keyword.length<=0){
                        this.getData()
                    }
                    else{
                        if(this.select.length<=0){
                                this.$message({
                                    type: 'info',
                                    message: '请选择查询条件啊'
                                })
                        }
                        else{
                            this.loading.dataStatus = true
                            this.$$api_permission_FindAdmin({userName:this.keyword},data=>{
                                this.loading.dataStatus = false
                                this.currentPage = data.PageIndex === 0 ? 1 : data.PageIndex
                                this.totalPage = data.TotalPage
                                this.totalCount = data.TotalCount
                                this.tableData= data.DataList
                            },
                            {
                                errFn:()=>{
                                         this.loading.dataStatus = false
                                }
                            })
                        }
                    }
                },
                removeAdmin(index, row) {
                    this.$confirm('确定要删除 '+row.UserName+' 吗?', '提示', {
                       confirmButtonText: '确定',
                       cancelButtonText: '取消',
                       type: 'warning'
                    }).then(() => {
                        this.$$api_permission_RemoveAdmin({ adminId : row.Id },data=>{
                            this.getData()
                            this.$message({
                                type: 'success',
                                message: data.Msg
                            });
                        })
                    }).catch(() => {
                          
                    });
                },
                disableAdmin(index, row) {
                    this.$confirm('确定要禁用 '+row.UserName+' 吗?', '提示', {
                       confirmButtonText: '确定',
                       cancelButtonText: '取消',
                       type: 'warning'
                    }).then(() => {
                        this.$$api_permission_DisableAdmin({ adminId : row.Id },data=>{
                            row.Status = 2
                            this.$message({
                                type: 'success',
                                message: data.Msg
                            })
                        })
                    }).catch((err) => {

                    })
                },
                enableAdmin(index, row) {
                   this.$confirm('确定要启用 '+row.UserName+' 吗?', '提示', {
                       confirmButtonText: '确定',
                       cancelButtonText: '取消',
                       type: 'warning'
                    }).then(() => {
                        this.$$api_permission_EnableAdmin({ adminId : row.Id },data=>{
                            row.Status = 1
                            this.$message({
                                type: 'success',
                                message: data.Msg
                            });
                        })
                    }).catch(() => {
                               
                    })
                },
                handleCurrentChange(val) {
                    this.currentPage = val
                    this.getData()
                },
                handleSelectionChange(val){
                    
                    this.selectionData=val;
                },
                removeSelection(){
                     if(this.selectionData.length>0)
                     {
                        var adminIds= this.selectionData.map(function(item){
                            return item.Id
                        })
                        this.$confirm('确定要删除选中的数据吗?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                        }).then(() => {
                            this.loading.dataStatus = true
                            this.$$api_permission_BatchRemoveAdmin({ adminIds : adminIds },data=>{
                                setTimeout(this.batchRemoveAdminCallback, 1500);
                            },{
                                errFn:()=>{
                                         this.loading.dataStatus = false
                                }
                            })
                        }).catch((err) => {
                            this.loading.dataStatus = false
                        });
                    }
                    else{
                        this.$message({
                                type: 'info',
                                message: '请选择要操作的数据'
                        });
                    }
                },
                batchRemoveAdminCallback(){ //批量删除的回调
                    this.selectionData = []
                    this.getData()
                    this.loading.dataStatus = false
                    this.$message({
                        type: 'success',
                        message: "删除成功"
                    });
                },
                dialogClose(){
                    this.showAddDialog = false
                }
        },
        created(){
             this.getData();
        },
        watch: {
            '$route' (to, from) {
                this.getData()
            },
            showAddDialog:function(){
                if(!this.showAddDialog){
                    this.$refs['adminForm'].resetFields();
                }
            }
        }
    }
  </script>

<style>
  .el-select .el-input {
    width: 100px;
  }
  .addDialog{
      width:400px;
  }
</style>
